package com.clickpaas.workinghours.dao.Impl;

import com.bizcloud.ipaas.tbba4bf83484b4ed2aacba581fbfeac4d.  d20210220155135.codegen.TimecardApi;
import com.bizcloud.ipaas.tbba4bf83484b4ed2aacba581fbfeac4d.  d20210220155135.model.*;
import com.clickpaas.workinghours.bean.WorkingHoursDTOBean;
import com.clickpaas.workinghours.config.AutoLoadConfig;
import com.clickpaas.workinghours.constant.ConfConstant;
import com.clickpaas.workinghours.constant.ConstantFile;
import com.clickpaas.workinghours.dao.TimeCardDao;
import com.clickpaas.workinghours.entity.PageInfoEntity;
import com.clickpaas.workinghours.entity.TimeCardEntity;
import com.clickpaas.workinghours.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class TimeCardDaoImpl implements TimeCardDao {

    @Resource
    private WorkingHoursDTOBean dtoBean;
    @Resource
    private TimecardApi timecardApi;
    /**
     * 根据条件查询
     *
     * @param timeCardDTO
     */
    private List<TimeCardDTOResponse> getDataByCondtion(TimeCardDTO timeCardDTO) {
        DataResponseListTimeCardDTO dataInfo = timecardApi.findTimeCardUsingPOST(timeCardDTO);
        if(null == dataInfo
                || null == dataInfo.getData()
                || dataInfo.getData().size()<=0
                || !"SUCCESS".equals(dataInfo.getMessage())){
            log.info("当前查询的数据：【{}】",dataInfo);
            return null;
        }
        return dataInfo.getData();
    }

    /**
     * 根据条件查询数据
     *
     * @param entity
     */
    @Override
    public List<TimeCardDTOResponse> queryDataInfo(TimeCardEntity entity) {
        TimeCardDTO tTimeCardDTO1 = dtoBean.timeCardDTO();
        try {
            SpringUtil.copyPropertiesIgnoreNull(entity,tTimeCardDTO1);
        }catch (Exception e){
            log.info("对象转换失败！转换的对象是：【{}】",entity);
        }
        return getDataByCondtion(tTimeCardDTO1);
    }

    /**
     * 查询所有项目数据
     */
    @Override
    public List<TimeCardDTOPageInfoResponse> queryDataInfo() {
        PageInfoEntity pageInfoEntity = new PageInfoEntity();
        pageInfoEntity.setPageNum(ConfConstant._PAGE_NUM);
        pageInfoEntity.setPageSize(ConfConstant._PAGE_SIZE);
        //分页查询
        PageInfoEntity tagetPageInfoEntity = getTotal(pageInfoEntity);
        if (null == tagetPageInfoEntity) return null;
        List<TimeCardDTOPageInfoResponse> listAll = new ArrayList<>();
        ArrayList<Future<DataResponseTimeCardDTOPageInfodata>> pageInfoList = new ArrayList<>();
        ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        try {
            for (int i = 1; i <= tagetPageInfoEntity.getRound(); i++) {
                int finalI = i;
                Future<DataResponseTimeCardDTOPageInfodata> submit = pool.submit(() -> queryPageInfo(finalI, tagetPageInfoEntity.getPageSize()));
                pageInfoList.add(submit);
            }
        }catch (Exception e){
            log.info("多线程查询数据异常：【{}】",e);
        }finally {
            pool.shutdown();
            try {
                pool.awaitTermination(3000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                log.info("多线程查询数据异常：【{}】",e);
            }
        }
        for (Future<DataResponseTimeCardDTOPageInfodata> p : pageInfoList) {
            try {
                DataResponseTimeCardDTOPageInfodata dtoPageInfo = p.get();
                if (null == dtoPageInfo || dtoPageInfo.getDataList().size()<=0)continue;
                listAll.addAll(dtoPageInfo.getDataList());
            } catch (Exception e) {
                log.info("取数据异常：【{}】",e);
            }
        }
        if (listAll.size() > 0) {
            return listAll;
        }

        return null;
    }

    /**
     * 工时填报数据入库
     */
    @Override
    public TimeCardSaveOrUpdateDataResponseObject insertDataInfo(TimeCardEntity entity) {
        TimeCardDTOUpdate timeCardDTOUpdate = dtoBean.timeCardDTOUpdate();
        try {
            SpringUtil.copyPropertiesIgnoreNull(entity,timeCardDTOUpdate);
        }catch (Exception e){
            log.info("对象转换失败！转换的对象是：【{}】",entity);
        }
        SaveOrUpdateTimeCardDTO saveInfo = new SaveOrUpdateTimeCardDTO();
        saveInfo.setQuery(dtoBean.timeCardDTOQuery());
        saveInfo.setUpdate(timeCardDTOUpdate);
        TimeCardSaveOrUpdateDataResponseObject responseObject = timecardApi.saveOrUpdateTimeCardUsingPOST(saveInfo);
        return responseObject;
    }

    /**
     * 工时填报数据更新
     * @param query
     * @param update
     * @return
     */
    @Override
    public TimeCardSaveOrUpdateDataResponseObject updateDataInfo(TimeCardEntity query,TimeCardEntity update) {
        TimeCardDTOQuery queryData = dtoBean.timeCardDTOQuery();
        TimeCardDTOUpdate updateData = dtoBean.timeCardDTOUpdate();

        try {
            SpringUtil.copyPropertiesIgnoreNull(query,queryData);
            SpringUtil.copyPropertiesIgnoreNull(update,updateData);
        }catch (Exception e){
            log.info("对象转换失败！转换的对象query:【{}】,update:【{}】",query,update);
        }
        SaveOrUpdateTimeCardDTO saveInfo = new SaveOrUpdateTimeCardDTO();
        saveInfo.setQuery(queryData);
        saveInfo.setUpdate(updateData);
        return timecardApi.saveOrUpdateTimeCardUsingPOST(saveInfo);
    }

    /**
     * 工时填报数据删除
     *
     * @param delete
     */
    @Override
    public boolean deleteDataInfo(TimeCardEntity delete) {
        TimeCardDTODelete timeCardDTO = dtoBean.timeCardDTODelete();
        ArrayList<TimeCardDTODelete> deleteDatas = new ArrayList<>();
        try {
            SpringUtil.copyPropertiesIgnoreNull(delete,timeCardDTO);
        }catch (Exception e){
            log.info("对象转换失败！转换的对象是：【{}】",delete);
        }
        deleteDatas.add(timeCardDTO);
        String message = timecardApi.deleteTimeCardUsingPOST(deleteDatas).getMessage();
        if (ConstantFile._MESSAGE.equals(message)){
            return true;
        }
        return false;
    }

    /**
     * 获取分页查询数据
     * @return
     */
    public PageInfoEntity getTotal(PageInfoEntity pageInfoEntity){
        Integer pageNum = pageInfoEntity.getPageNum();
        Integer pageSize = pageInfoEntity.getPageSize();
        DataResponseTimeCardDTOPageInfodata pageInfodata = queryPageInfo(pageNum, pageSize);
        if (null != pageInfodata
                && StringUtils.isNotBlank(pageInfodata.getTotal())){
            //查询总数
            String total = pageInfodata.getTotal();
            double ceil = Math.ceil(Double.valueOf(total) / Double.valueOf(AutoLoadConfig.PAGE_SIZE));
            //分页查询次数
            Long round = Math.round(ceil);
            pageInfoEntity.setTotal(Integer.valueOf(total));
            pageInfoEntity.setPageSize(AutoLoadConfig.PAGE_SIZE);
            pageInfoEntity.setRound(round.intValue());
            return pageInfoEntity;
        }
        return null;
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    public DataResponseTimeCardDTOPageInfodata queryPageInfo(Integer pageNum, Integer pageSize) {
        TimeCardDTOPageInfo pageInfo = dtoBean.timeCardDTOPageInfo();
        pageInfo.set$PageNum(pageNum);
        pageInfo.set$PageSize(pageSize);
        DataResponseTimeCardDTOPageInfo pageInfoData = timecardApi.findPageInfoTimeCardUsingPOST(pageInfo);
        if (null == pageInfoData || null == pageInfoData.getData())return null;
        return pageInfoData.getData();
    }

}
